package com.ezlearning.platform.services.core.impl;

import com.ezlearning.platform.dto.StudentDto;
import com.ezlearning.platform.model.Student;
import com.ezlearning.platform.repositories.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {

    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    /**
     * 创建学生记录
     * @param studentDto 包含学生信息的 DTO
     */
    public void create(StudentDto studentDto) {
        String firstName = studentDto.getFirstName();
        String lastName = studentDto.getLastName();
        String email = studentDto.getEmail();
        String description = studentDto.getDescription();
        String details = studentDto.getDetails();
        String imgurl = studentDto.getImgurl();

        Student student = new Student(firstName, lastName, email, description, details, imgurl);
        studentRepository.save(student);
    }

    /**
     * 获取所有学生记录
     * @return 学生列表
     */
    public List<Student> getAll() {
        return studentRepository.findAll();
    }

    /**
     * 更新学生记录
     * @param student 包含更新信息的学生对象
     */
    public void update(Student student) {
        Student currentStudent = studentRepository.findById(student.getStudentId()).orElseThrow(() ->
                new IllegalArgumentException("Student not found with ID: " + student.getStudentId()));

        currentStudent.setFirstName(student.getFirstName());
        currentStudent.setLastName(student.getLastName());
        currentStudent.setEmail(student.getEmail());
        currentStudent.setDescription(student.getDescription());
        currentStudent.setDetails(student.getDetails());
        currentStudent.setImgurl(student.getImgurl());

        studentRepository.save(currentStudent);
    }

    /**
     * 局部更新学生记录
     * @param student 包含更新详情信息的学生对象
     */
    public void patch(Student student) {
        Student current = studentRepository.findById(student.getStudentId()).orElseThrow(() ->
                new IllegalArgumentException("Student not found with ID: " + student.getStudentId()));

        current.setDetails(student.getDetails());

        studentRepository.save(current);
    }

    /**
     * 删除学生记录
     * @param student 要删除的学生对象
     */
    public void delete(Student student) {
        studentRepository.delete(student);
    }
}
